{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "0894a735",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig\n",
    "import torch\n",
    "import json\n",
    "\n",
    "TORCH_DTYPE = 'bfloat16'\n",
    "nf4_config = BitsAndBytesConfig(\n",
    "    load_in_4bit=True,\n",
    "    bnb_4bit_quant_type='nf4',\n",
    "    bnb_4bit_use_double_quant=True,\n",
    "    bnb_4bit_compute_dtype=getattr(torch, TORCH_DTYPE)\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "6daae66f",
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained('mesolitica/malaysian-tinyllama-1.1b-16384-instructions')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "0da5df04",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = AutoModelForCausalLM.from_pretrained(\n",
    "    'mesolitica/malaysian-tinyllama-1.1b-16384-instructions',\n",
    "    use_flash_attention_2 = True,\n",
    "    quantization_config = nf4_config\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f18b9442",
   "metadata": {},
   "outputs": [],
   "source": [
    "def parse_llama_chat(messages, function_call = None):\n",
    "\n",
    "    system = messages[0]['content']\n",
    "    user_query = messages[-1]['content']\n",
    "\n",
    "    users, assistants = [], []\n",
    "    for q in messages[1:-1]:\n",
    "        if q['role'] == 'user':\n",
    "            users.append(q['content'])\n",
    "        elif q['role'] == 'assistant':\n",
    "            assistants.append(q['content'])\n",
    "\n",
    "    texts = [f'<s>[INST] <<SYS>>\\n{system}\\n<</SYS>>\\n\\n']\n",
    "    if function_call:\n",
    "        fs = []\n",
    "        for f in function_call:\n",
    "            f = json.dumps(f, indent=4)\n",
    "            fs.append(f)\n",
    "        fs = '\\n\\n'.join(fs)\n",
    "        texts.append(f'\\n[FUNCTIONCALL]\\n{fs}\\n')\n",
    "    for u, a in zip(users, assistants):\n",
    "        texts.append(f'{u.strip()} [/INST] {a.strip()} </s><s>[INST] ')\n",
    "    texts.append(f'{user_query.strip()} [/INST]')\n",
    "    prompt = ''.join(texts).strip()\n",
    "    return prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "07881cfc",
   "metadata": {},
   "outputs": [],
   "source": [
    "messages = [\n",
    "    {'role': 'system', 'content': 'awak adalah AI yang mampu jawab segala soalan'},\n",
    "    {'role': 'user', 'content': 'kwsp tu apa'}\n",
    "]\n",
    "prompt = parse_llama_chat(messages)\n",
    "inputs = tokenizer([prompt], return_tensors='pt', add_special_tokens=False).to('cuda')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "67d3c231",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'<s> [INST] <<SYS>>\\nawak adalah AI yang mampu jawab segala soalan\\n<</SYS>>\\n\\nkwsp tu apa [/INST] KWSP bermaksud Kumpulan Wang Persaraan. </s>'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "generate_kwargs = dict(\n",
    "    inputs,\n",
    "    max_new_tokens=1024,\n",
    "    top_p=0.95,\n",
    "    top_k=50,\n",
    "    temperature=0.9,\n",
    "    do_sample=True,\n",
    "    num_beams=1,\n",
    ")\n",
    "r = model.generate(**generate_kwargs)\n",
    "tokenizer.decode(r[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4efaf03f",
   "metadata": {},
   "outputs": [],
   "source": [
    "messages = [\n",
    "    {'role': 'system', 'content': 'awak adalah AI yang mampu jawab segala soalan'},\n",
    "    {'role': 'user', 'content': 'awat malaysia ada jabatan koko, malaysia bukan buat keluaq koko banyak pun'}\n",
    "]\n",
    "prompt = parse_llama_chat(messages)\n",
    "inputs = tokenizer([prompt], return_tensors='pt', add_special_tokens=False).to('cuda')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "bdc41dda",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<s> [INST] <<SYS>>\n",
      "awak adalah AI yang mampu jawab segala soalan\n",
      "<</SYS>>\n",
      "\n",
      "awat malaysia ada jabatan koko, malaysia bukan buat keluaq koko banyak pun [/INST] Jabatan ini bertanggungjawab untuk mengeluarkan dan mengagihkan produk koko ke pasaran tempatan dan antarabangsa. Mereka juga menyumbang kepada pembangunan industri koko dan memastikan penggunaan sumber asli yang bertanggungjawab. Selain itu, mereka menjalankan penyelidikan dan inovasi untuk meningkatkan proses pengeluaran dan meningkatkan daya saing produk koko. </s>\n"
     ]
    }
   ],
   "source": [
    "generate_kwargs = dict(\n",
    "    inputs,\n",
    "    max_new_tokens=1024,\n",
    "    top_p=0.95,\n",
    "    top_k=50,\n",
    "    temperature=0.9,\n",
    "    do_sample=True,\n",
    "    num_beams=1,\n",
    ")\n",
    "r = model.generate(**generate_kwargs)\n",
    "print(tokenizer.decode(r[0]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "05afbe68",
   "metadata": {},
   "outputs": [],
   "source": [
    "f2 = {\n",
    "    'name': 'parse_entities',\n",
    "    'description': 'extract entities from the text',\n",
    "    'parameters': {\n",
    "        'type': 'object',\n",
    "        'properties': {\n",
    "            'drink': {\n",
    "                'type': 'string',\n",
    "                'description': 'drink name',\n",
    "            },\n",
    "            'event': {\n",
    "                'type': 'string',\n",
    "                'description': 'event name',\n",
    "            },\n",
    "            'person_name': {\n",
    "                'type': 'string',\n",
    "                'description': 'person name',\n",
    "            }\n",
    "        },\n",
    "        'required': [\n",
    "            'drink',\n",
    "            'event',\n",
    "            'person_name'\n",
    "        ]\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "17c56e61",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<s> [INST] <<SYS>>\n",
      "awak adalah AI yang mampu jawab segala soalan\n",
      "<</SYS>>\n",
      "\n",
      "\n",
      "[FUNCTIONCALL]\n",
      "{\n",
      "    \"name\": \"parse_entities\",\n",
      "    \"description\": \"extract entities from the text\",\n",
      "    \"parameters\": {\n",
      "        \"type\": \"object\",\n",
      "        \"properties\": {\n",
      "            \"drink\": {\n",
      "                \"type\": \"string\",\n",
      "                \"description\": \"drink name\"\n",
      "            },\n",
      "            \"event\": {\n",
      "                \"type\": \"string\",\n",
      "                \"description\": \"event name\"\n",
      "            },\n",
      "            \"person_name\": {\n",
      "                \"type\": \"string\",\n",
      "                \"description\": \"person name\"\n",
      "            }\n",
      "        },\n",
      "        \"required\": [\n",
      "            \"drink\",\n",
      "            \"event\",\n",
      "            \"person_name\"\n",
      "        ]\n",
      "    }\n",
      "}\n",
      "nama saya husein bin zolkepli, saya sekarang berada di putrajaya merdeka 2023 sambil minum teh o ais [/INST] <functioncall> {\"name\": \"parse_entities\", \"arguments\": '{\"drink\": \"teh o ais\", \"event\": \"Merdeka 2023\", \"person_name\": \"Husein bin Zolkepli\"}'} \n",
      "\n",
      "\n",
      "<functioncall> {\"entities\": [{\"name\": \"Husein bin Zolkepli\", \"confidence\": 0.95}]} </s>\n"
     ]
    }
   ],
   "source": [
    "messages = [\n",
    "    {'role': 'system', 'content': 'awak adalah AI yang mampu jawab segala soalan'},\n",
    "    {'role': 'user', 'content': 'nama saya husein bin zolkepli, saya sekarang berada di putrajaya merdeka 2023 sambil minum teh o ais'}\n",
    "]\n",
    "prompt = parse_llama_chat(messages, function_call = [f2])\n",
    "inputs = tokenizer([prompt], return_tensors='pt', add_special_tokens=False).to('cuda')\n",
    "generate_kwargs = dict(\n",
    "    inputs,\n",
    "    max_new_tokens=128,\n",
    "    top_p=0.95,\n",
    "    top_k=50,\n",
    "    temperature=0.9,\n",
    "    do_sample=True,\n",
    "    num_beams=1,\n",
    ")\n",
    "r = model.generate(**generate_kwargs)\n",
    "print(tokenizer.decode(r[0]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f1897af4",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
